package com.cwd.arm.common.util;

import com.googlecode.aviator.AviatorEvaluator;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 计算引擎
 * Created by yan on 22-2-17.
 */
public class AviatorEvaluatorUtil {

    /**
     * 实时毛利率
     * 利润率为合计支出/合同金额（有结算金额后除结算金额）
     */
    private static final String GROSS_RATE = "1 - ( payAmount / contractAmount )";

    /**
     * 是否毛利率预警
     */
    private static final String GROSS_RATE_WARN_AU = " payAmount / contractAmount  > 0.75";

    /**
     * 实时毛利率是否需要预警
     */
    private static final String GROSS_RATE_WARN = "grossRate < 0.25";

    /**
     * 是否支出预警
     */
    private static final String PAY_WARN = " payAmount / receivedAmount  > cashRate";


    public static BigDecimal grossRate(BigDecimal payAmount, BigDecimal contractAmount){
        Map<String, Object> map = getGrossMap(payAmount, contractAmount);
        Object rt = AviatorEvaluator.execute(GROSS_RATE, map);
        return BigDecimalUtil.scaleRate((BigDecimal)rt);
    }

    public static Boolean grossRateWarn(BigDecimal grossRate){
        Map<String, Object> map = new HashMap();
        map.put("grossRate",grossRate);
        Object rt = AviatorEvaluator.execute(GROSS_RATE_WARN, map);
        return (Boolean) rt;
    }

    public static Boolean grossRateWarn(BigDecimal payAmount, BigDecimal contractAmount){
        Map<String, Object> map = getGrossMap(payAmount, contractAmount);
        Object rt = AviatorEvaluator.execute(GROSS_RATE_WARN_AU, map);
        return (Boolean) rt;
    }

    public static Boolean grossPayWarn(BigDecimal payAmount, BigDecimal receivedAmount,BigDecimal cashRate){
        if(!BigDecimalUtil.hasRecord(receivedAmount) || !BigDecimalUtil.hasRecord(cashRate)){
            return false;
        }
        Map<String, Object> map = new HashMap();
        map.put("payAmount",payAmount);
        map.put("receivedAmount",receivedAmount);
        map.put("cashRate",cashRate);
        Object rt = AviatorEvaluator.execute(PAY_WARN, map);
        return (Boolean) rt;
    }

    private static Map<String, Object> getGrossMap(BigDecimal payAmount, BigDecimal contractAmount) {
        Map<String, Object> map = new HashMap();
        map.put("payAmount",payAmount);
        map.put("contractAmount",contractAmount);
        return map;
    }
}
